/**
 * SSE 聊天 API - RuoYi 风格
 * 入参出参全用 any，字段直接拼字符串
 */

import type { SSEMessageCallback, SSEErrorCallback, SSECompleteCallback, SSEChatController } from '../types'

/**
 * 发送 SSE 聊天消息
 */
export const sendSSEChat = (
  message: string,
  onMessage: SSEMessageCallback,
  onError?: SSEErrorCallback,
  onComplete?: SSECompleteCallback
): Promise<void> => {
  const url = `/sse-api/chat?message=${encodeURIComponent(message)}`

  return fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'text/event-stream'
    },
    // 添加 keepalive 选项
    keepalive: true
  })
    .then(response => {
      console.log('[SSE] fetch 响应接收, status:', response.status)
      if (!response.ok) {
        throw new Error(`HTTP错误! 状态码: ${response.status}`)
      }

      if (!response.body) {
        throw new Error('响应体为空')
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder('utf-8')
      let buffer = '' // 添加缓冲区

      console.log('[SSE] 开始设置流读取器')

      // 递归读取流数据
      const readStream = (): Promise<void> => {
        console.log('[SSE] 开始读取下一个chunk...')
        return reader.read()
          .then(({ done, value }) => {
            console.log('[SSE] reader.read() 完成, done:', done, 'value长度:', value?.length)
            if (done) {
              console.log('[SSE] 流读取完成')
              // 处理剩余的 buffer
              if (buffer.trim()) {
                const lines = buffer.split('\n')
                lines.forEach(line => {
                  if (line.startsWith('data: ')) {
                    const data = line.substring(6).trim()
                    if (data && data !== '[DONE]') {
                      onMessage(data)
                    }
                  }
                })
              }
              if (onComplete) onComplete()
              return Promise.resolve()
            }

            // 解码数据并拼接到缓冲区
            const chunk = decoder.decode(value, { stream: true })
            buffer += chunk
            
            // 按行分割
            const lines = buffer.split('\n')
            // 保留最后一行在 buffer 中，因为它可能不完整
            buffer = lines.pop() || ''

            // 处理完整的行
            lines.forEach(line => {
              if (line.startsWith('data: ')) {
                const data = line.substring(6).trim()
                if (data && data !== '[DONE]') {
                  onMessage(data)
                } else if (data === '[DONE]') {
                  console.log('[SSE] 收到 [DONE] 标记')
                }
              }
            })

            console.log('[SSE] 继续读取下一个chunk...')
            return readStream()
          })
          .catch(error => {
            console.error('读取流数据错误:', error)
            console.error('错误堆栈:', error.stack)
            if (onError) onError(error)
            // 不要 throw error，这会中断连接
            return Promise.resolve()
          })
      }

      return readStream()
    })
    .catch(error => {
      console.error('SSE请求错误:', error)
      if (onError) onError(error)
      // 不要 throw error，避免未捕获的 Promise rejection
      return Promise.resolve()
    })
}

/**
 * 创建可中断的 SSE 聊天请求
 */
export const createAbortableSSEChat = (
  message: string,
  onMessage: SSEMessageCallback,
  onError?: SSEErrorCallback,
  onComplete?: SSECompleteCallback
): { promise: Promise<void>, controller: SSEChatController } => {
  const abortController = new AbortController()
  const url = `/sse-api/chat?message=${encodeURIComponent(message)}`

  const promise = fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'text/event-stream'
    },
    signal: abortController.signal
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP错误! 状态码: ${response.status}`)
      }

      if (!response.body) {
        throw new Error('响应体为空')
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder('utf-8')
      let buffer = ''

      const readStream = (): Promise<void> => {
        return reader.read()
          .then(({ done, value }) => {
            if (done) {
              if (buffer.trim()) {
                const lines = buffer.split('\n')
                lines.forEach(line => {
                  if (line.startsWith('data: ')) {
                    const data = line.substring(6).trim()
                    if (data && data !== '[DONE]') {
                      onMessage(data)
                    }
                  }
                })
              }
              if (onComplete) onComplete()
              return Promise.resolve()
            }

            const chunk = decoder.decode(value, { stream: true })
            buffer += chunk
            
            const lines = buffer.split('\n')
            buffer = lines.pop() || ''

            lines.forEach(line => {
              if (line.startsWith('data: ')) {
                const data = line.substring(6).trim()
                if (data && data !== '[DONE]') {
                  onMessage(data)
                }
              }
            })

            return readStream()
          })
          .catch(error => {
            // 中断错误不传递
            if (error.name === 'AbortError') {
              console.log('SSE请求已被中断')
              return Promise.resolve()
            }
            throw error
          })
      }

      return readStream()
    })
    .catch(error => {
      // 中断错误不调用 onError
      if (error.name === 'AbortError') {
        console.log('SSE请求已被中断')
        return Promise.resolve()
      }

      console.error('SSE请求错误:', error)
      if (onError) onError(error)
      throw error
    })

  return {
    promise,
    controller: {
      abort: () => abortController.abort()
    }
  }
}
